import fs from 'fs';
import readline from 'readline';
import { runPnpmCommand } from './utils/run-pnpm.js';
import Pinyin from './utils/ChinesePY.js';
import BaiduTranslate from "./utils/BaiduTranslate.js"; //引入百度翻译文件
import AliyunTranslate from "./utils/AliyunTranslate.js"; // 引入阿里云翻译文件

const reg =
  /[\u4e00-\u9fa5]|([\u4e00-\u9fa5]*)([\u3002\uff1b\uff0c\uff1a\u2018\u2019\u201c\u201d\uff08\uff09\u3001\uff1f\u300a\u300b\uff01\u2014\u2026\u2013\uff0e])([\u4e00-\u9fa5]*)/g; //中文正则
import path from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);


function readFileToArr(fReadName) {
  //提取中文
  return new Promise((resolve, reject) => {
    console.log(`正在处理${fReadName}`);
    let fRead = fs.createReadStream(fReadName);
    let objReadline = readline.createInterface({
      input: fRead,
    });
    let arr = new Array();
    objReadline.on('line', function (line) {
      if (line.match(reg)) {
        arr.push(line.match(reg));
      }
      // console.log('line:'+ line);
    });
    objReadline.on('close', function () {
      //    console.log('close',arr);
      resolve(arr);
    });
  });
}

/**
 * @description 得到所有文件
 */

let allFile = [];
const fileDisplay = (filePath, callback) => {
  //遍历所有文件
  //根据文件路径读取文件，返回文件列表
  let files = fs.readdirSync(filePath);
  //遍历读取到的文件列表
  files.forEach((filename, index) => {
    //获取当前文件的绝对路径
    let filedir = path.join(filePath, filename);
    let stats = fs.statSync(filedir);
    if (stats) {
      let isFile = stats.isFile(); //是文件
      let isDir = stats.isDirectory(); //是文件夹
      if (isFile) {
        // console.log(filedir)
        allFile.push(filedir);
      }
      if (isDir) {
        fileDisplay(filedir); //递归，如果是文件夹，就继续遍历该文件夹下面的文件
      }
    }
  });
  callback && callback.call();
};

/**
 * @description 处理中文 得到简拼作为key
 * @param {Arrary} chinesewords //中文集合
 * @return {enkey:word}
 */
function handleChinese(chinesewords, originObj) {
  let temp = originObj || {};
  chinesewords.forEach((word, index) => {
    let key = Pinyin.GetJP(word);
    if (key.length > 5) {
      //一般认为取简拼前五位
      key = key.substr(0, 5);
    }

    if (temp.hasOwnProperty(key) && temp[key] != word) {
      let samekeyNum = 0;
      for (let keyName in temp) {
        let s = keyName.split(key);
        if (s.length > 1 && !isNaN(s[1] * 1)) {
          samekeyNum++;
        }
      }
      key = key + samekeyNum; //key加索引
    }
    temp[key] = word;
  });
  return temp;
}

// var childProcess = require('child_process');
import childProcess from 'child_process';
function runScript(scriptPath, callback) {
  // keep track of whether callback has been invoked to prevent multiple invocations
  var invoked = false;

  var process = childProcess.fork(scriptPath);

  // listen for errors as they may prevent the exit event from firing
  process.on('error', function (err) {
    if (invoked) return;
    invoked = true;
    callback(err);
  });

  // execute the callback once the process has finished running
  process.on('exit', function (code) {
    if (invoked) return;
    invoked = true;
    var err = code === 0 ? null : new Error('exit code ' + code);
    callback(err);
  });
}



//获取文件内容
function getFileContent(filePath) {
  return new Promise((resolve, reject) => {
    fs.readFile(filePath, 'utf8', (err, data) => {
      if (err) {
        resolve(null);
      } else {
        resolve(data);
      }
    });
  });
}
const main = async (config) => {

  let translate = null;
  const toTranslateLang = config.toTranslateLang;
  const autoReWriter = config.autoReWriter;


  if (config.engine == 'baidu') {
    translate = new BaiduTranslate(config.baidu);
  } else {
    translate = new AliyunTranslate(config.aliyun);
  }

  const batchTranslation = async (chineseObj) => {
    for (let index = 0; index < toTranslateLang.length; index++) {
      const item = toTranslateLang[index];
      const res = await translate(chineseObj, { from: "zh", to: item,scene:config.scene},config.professionalMode)
      fs.writeFileSync(`dist/lang/${item}.json`, JSON.stringify(res, null, 2));
    }
  }

  try {
    //step1 借助i18n-text-tools 提取vue文件中的中文并替换
    await runPnpmCommand('i18n:extract');
    let zhData = await getFileContent(
      path.resolve('./dist/.translation_map.json')
    );
    zhData = JSON.parse(zhData);
    let wordsMap = new Set();
    const tempObj = {};
    for (let key in zhData) {
      const word = zhData[key];
      wordsMap.add(word);
    }
    // 中文json 数据，如果有中文json数据则为补丁翻译模式，否则全量翻译
    const sourceDate = await getFileContent(path.resolve('./dist/lang/zh.json'))
    const chineseObj = handleChinese(Array.from(wordsMap), sourceDate ? JSON.parse(sourceDate) : null);
    for (let key in zhData) {
      const word = zhData[key];
      for (let zhKey in chineseObj) {
        if (word === chineseObj[zhKey]) {
          tempObj[key] = zhKey;
        }
      }
    }
    // 写入中文文件
    fs.writeFileSync('dist/lang/zh.json', JSON.stringify(chineseObj, null, 2));

    //写入key对照文件，以方便后面重写替换
    fs.writeFileSync(
      `dist/.translation_temp.json`,
      `${JSON.stringify(tempObj, null, 2)}`
    );
    // 如果中文json存在的走补丁翻译否则走全量翻译
    if (sourceDate) {
      runScript(path.join(__dirname, './pathTranslattionJson.js'), function (err) {
        if (err) throw err;
        console.log('翻译补丁更新成功');
      });
    } else {
      batchTranslation(chineseObj)
    }
    if (autoReWriter) { //是否自动
      setTimeout(() => {
        let srcriptJsPath = path.join(__dirname, './reWrite.js')
        runScript(srcriptJsPath, function (err) {
          if (err) throw err;
          console.log('翻译替换完成');
        });
      }, 1000)
    }

  } catch (err) {
    console.log(err);
  }
};

export default main;
// main();
